package com.manager.devicemanager.scheduler;

import com.manager.devicemanager.common.DataSourceNameEnum;
import com.manager.devicemanager.service.CommonCleanupService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Component
@Slf4j
@RequiredArgsConstructor
@RestController
public class MultiDbCleanupScheduler {

    @Autowired

    private final CommonCleanupService commonCleanupService;

    /**
     * 定时执行所有数据库的清理任务
     */
    @Scheduled(cron = "${cleanup.cron}")
    @GetMapping("/cleanup")
    public void scheduleMultiDbCleanup() {
        log.info("===== 开始执行多数据库清理任务 =====");
        // 定义需要清理的数据源类型
        DataSourceNameEnum[] dataSourceTypes = {
                DataSourceNameEnum.ICBOARDCONFIG,
                DataSourceNameEnum.ICBOARDATA,
                DataSourceNameEnum.PDBOARDCONFIG,
                DataSourceNameEnum.PDBOARDATA
        };

        // 遍历数据源类型
        for (DataSourceNameEnum type : dataSourceTypes) {
            // 执行基础数据源清理
            commonCleanupService.asyncCleanupDatabase(type.getDataSourceName());
            // 若有带后缀 1 的数据源，执行清理
            if (type == DataSourceNameEnum.ICBOARDCONFIG || type == DataSourceNameEnum.ICBOARDATA) {
                commonCleanupService.asyncCleanupDatabase(type.getDataSourceName() + "1");
            }
        }

        log.info("===== 多数据库清理任务调度完成 =====");
    }

}
